import {createRouter, createWebHashHistory, createWebHistory} from 'vue-router'
import Home from "@/views/Home.vue";
import Movie from "@/views/Movie.vue";
import About from "@/views/About.vue";
import Tab1 from "@/views/Tab1.vue";
import Tab2 from "@/views/Tab2.vue";
import User from "@/views/User.vue";

const NotFound = {
    template: '<div>没有找到你要访问的页面 404，目标位置：{{$route.params.path}}</div>'
}
// 路由记录合集
/*const routes = [
    {
        path: "/",
        component: Home
    },
    {
        path: "/home",
        component: Home
    },
    {
        path: "/movie/:id?",
        name: "movie",
        component: Movie,
        props: true
    },
    {
        path: "/about",
        component: About,
        redirect: "/about/tab1",
        children: [{path: "tab1", component: Tab1}, {path: "tab2", component: Tab2}]
    },
    {
        path: "/film",
        redirect: "/movie"
    },
    // 动态字段以冒号开始
    {
        path: '/user/:id(\\d+)?',
        component: User
    },
    {
        path: '/user/:username/posts/:id',
        component: User
    },
    // {
    //     path: '/:pathMatch(.*)*',
    //     name: 'NotFuond',
    //     component: NotFuond
    // }
]*/
let routes = [
    {
        path: "/",
        component: Home
    },
    {
        path: "/:id(\\d{3})?",
        name: "user",
        component: User
    },
    {
        name: "movie",
        path: "/movie/:id?",
        component: Movie
    },
    {
        path: "/about",
        component: About,
        redirect: "/about/tab1",
        children: [{path: "tab1", component: Tab1}, {path: "tab2", component: Tab2}]
    },
    {
        path: "/film",
        redirect: "/movie"
    },
    {
        path: "/:path(.*)*",
        component: NotFound
    },
    {
        path: "/login",
        name: "login",
        component: () => import("@/views/Login.vue")
    }
];

// 创建路由器
const router = createRouter({
    history: createWebHistory(), //指定路由模式为hash模式（兼容性好，但带#）
    routes
})

const whitePathList = ['/login'];
// 全局导航守卫
router.beforeEach(async (to, from, next) => {
    const token = localStorage.getItem("ACCESS_TOKEN");
    console.log(token)
    if (token) {
        console.log(to)
        console.log(from)
        if (to.path === '/login') {
            next('/') // 去往首页
        } else {
            next()
        }
    } else {
        if (whitePathList.indexOf(to.path) > -1) {
            next()
        } else {
            next("/login");
        }
    }
})

// 导出
export default router